import React, {FC, useCallback, useEffect, useImperativeHandle, useMemo, useState} from "react";
import {Checkbox, Col, Divider, Row} from "antd";
import './css/CTableCustomSearch.less'
import {getLocale} from "../../../i18n/i18n.tsx";

interface CtableCustomSearchProps {
    init: any,
    columnApi: any
}

const CTableCustomSearch: FC<CtableCustomSearchProps> = (props) => {

    const [checkedList, setCheckedList] = useState([]);
    const [list, setList] = useState([]);


    const onChange = useCallback((checkKeys: any) => {
        setCheckedList(checkKeys)
    }, [])

    const onCheckAllChange = useCallback((e: any) => {
        if (e.target.checked) {
            let keys: any = list.map((item: any) => item.field)
            setCheckedList(keys);
        } else {
            setCheckedList([]);
        }
    }, [list])

    const getList = useCallback(() => {
        let list: any = [];
        props.columnApi.columnModel.columnDefs.forEach((item: any) => {
            if (item.headerName) {
                list.push(item)
            }
        })
        setList(list)
    }, [props.columnApi])

    useEffect(() => {
        getList()
    }, [])

    useImperativeHandle(props.init, () => {
        return {
            checkedList: checkedList
        }
    });

    const renderCtableCustomSearch = useMemo(() => {
        return (
            <div className="sf_core_ctable_custom_search">
                <Checkbox indeterminate={checkedList.length > 0 && checkedList.length < list.length}
                          onChange={onCheckAllChange} checked={list.length === checkedList.length}>
                    {getLocale("全选", "Select All")}
                </Checkbox>
                <Divider style={{margin: '10px 0'}}/>
                <Checkbox.Group style={{width: '100%'}} value={checkedList} onChange={onChange}>
                    <Row>
                        {
                            list.map((item: any) => {
                                return (
                                    <Col span={24} className="sf_core_ctable_custom_search_item" key={item.field}>
                                        <Checkbox value={item.field}>{item.headerName}</Checkbox>
                                    </Col>
                                )
                            })
                        }
                    </Row>
                </Checkbox.Group>
            </div>
        )
    }, [props, list, checkedList]);

    return (renderCtableCustomSearch);
};

export default React.memo(CTableCustomSearch);